package cn.admobiletop.adsuyi.adapter.toutiao.listener;

import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;

import java.util.List;

import cn.admobiletop.adsuyi.ad.ADSuyiBannerAd;
import cn.admobiletop.adsuyi.ad.listener.ADSuyiBannerAdListener;
import cn.admobiletop.adsuyi.adapter.toutiao.data.BannerAdInfo;
import cn.admobiletop.adsuyi.config.ADSuyiErrorConfig;
import cn.admobiletop.adsuyi.util.ADSuyiAdUtil;
import cn.admobiletop.adsuyi.util.ADSuyiLogUtil;

/**
 * @author ciba
 * @description Banner广告监听器
 * @date 2020/4/2
 */
public class BannerAdListener extends BaseAdListener<ADSuyiBannerAdListener> implements TTAdNative.NativeExpressAdListener {
    private ADSuyiBannerAd bannerAd;
    private BannerAdInfo bannerAdInfo;
    private int exposedViewHashCode;
    private Handler handler = new Handler(Looper.getMainLooper());

    public BannerAdListener(ADSuyiBannerAd bannerAd, String platformPosId, ADSuyiBannerAdListener adListener) {
        super(platformPosId, adListener);
        this.bannerAd = bannerAd;
    }

    @Override
    public void onError(final int code, final String message) {
        if (handler != null) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    onAdFailed(code, message);
                }
            });
        }
    }

    @Override
    public void onNativeExpressAdLoad(List<TTNativeExpressAd> expressAdList) {
        if (expressAdList == null
                || expressAdList.isEmpty()
                || expressAdList.get(0) == null
                || expressAdList.get(0).getExpressAdView() == null) {
            if (handler != null) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onAdFailed(ADSuyiErrorConfig.AD_FAILED_AD_IS_EMPTY, ADSuyiErrorConfig.MSG_AD_FAILED_AD_IS_EMPTY);
                    }
                });
            }
            return;
        }

        if (getAdListener() != null && !ADSuyiAdUtil.isReleased(bannerAd) && bannerAd.getContainer() != null) {
            TTNativeExpressAd ttNativeExpressAd = expressAdList.get(0);
            this.bannerAdInfo = new BannerAdInfo(bannerAd.getActivity(), getPlatformPosId());
            this.bannerAdInfo.setAdapterAdInfo(ttNativeExpressAd);
            this.bannerAdInfo.setAdListener(getAdListener());

            // 设置广告刷新间隔
            if (bannerAd.getAutoRefreshInterval() > 0) {
                ttNativeExpressAd.setSlideIntervalTime((int) bannerAd.getAutoRefreshInterval() * 1000);
            }

            try {
                // 设置广告事件
                ttNativeExpressAd.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
                    @Override
                    public void onAdClicked(View view, int i) {
                        if (handler != null) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (getAdListener() != null && bannerAdInfo != null) {
                                        getAdListener().onAdClick(bannerAdInfo);
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onAdShow(View view, int i) {
                        if (view != null && getAdListener() != null) {
                            // 获取当前视图的hashCode
                            int hashCode = view.hashCode();

                            if (exposedViewHashCode != hashCode) {
                                // 如果当前hashCode和上次展示的hashCode不一致
                                if (exposedViewHashCode != 0
                                        && !ADSuyiAdUtil.isReleased(bannerAd)
                                        && getAdListener() != null
                                        && bannerAdInfo != null
                                        && bannerAdInfo.getAdapterAdInfo() != null) {
                                    // 如果不为0，则说明非第一次曝光，非第一次曝光需要再次走成功回调
                                    TTNativeExpressAd adapterAdInfo = bannerAdInfo.getAdapterAdInfo();
                                    bannerAdInfo = new BannerAdInfo(bannerAd.getActivity(), getPlatformPosId());
                                    bannerAdInfo.setAdapterAdInfo(adapterAdInfo);
                                    bannerAdInfo.setAdListener(getAdListener());

                                    if (handler != null) {
                                        handler.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                getAdListener().onAdReceive(bannerAdInfo);
                                            }
                                        });
                                    }
                                }

                                // 更新hashCode
                                exposedViewHashCode = hashCode;
                                if (handler != null) {
                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            // 曝光回调
                                            getAdListener().onAdExpose(bannerAdInfo);
                                        }
                                    });
                                }
                            }
                        }
                    }

                    @Override
                    public void onRenderFail(View view, final String msg, final int code) {
                        if (handler != null) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    if (exposedViewHashCode == 0) {
                                        onAdFailed(code, "banner render fail, " + msg);
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onRenderSuccess(final View view, float v, float v1) {
                        if (handler != null) {
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    // 此回调目前只会第一次回调
                                    if (!ADSuyiAdUtil.isReleased(bannerAd)) {
                                        try {
                                            // 将广告视图添加到容器中
                                            if (!ADSuyiAdUtil.isReleased(bannerAd) && bannerAd.getContainer() != null && view != null) {
                                                bannerAd.getContainer().removeAllViews();
                                                bannerAd.getContainer().addView(view, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        // 广告获取成功回调
                                        if (getAdListener() != null && bannerAdInfo != null) {
                                            getAdListener().onAdReceive(bannerAdInfo);
                                        }
                                    }
                                }
                            });
                        }
                    }
                });
                ttNativeExpressAd.render();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 释放资源
     */
    @Override
    public void release() {
        super.release();
        bannerAd = null;
        if (bannerAdInfo != null) {
            bannerAdInfo.release();
            bannerAdInfo = null;
        }

        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }
}
